package com.lxp.design.shop.order.controller;

import com.lxp.design.shop.order.service.PersonService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;




/**
 * @author LaiXiaoPeng
 * @version 1.0
 * @date 2021/7/19 11:42
 */
@RestController
@Slf4j
@RequestMapping("/person")
public class PersonController{

    @Autowired
    private PersonService personService;
    @GetMapping("/list")
    public String getPersons(){
        return "success";
    }

    @GetMapping("/success")
    public String success(){
        return "success";
    }

    @GetMapping("/timeOut")
    @HystrixCommand(fallbackMethod ="timeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "10000")
    })
    public String timeOut(){
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "timeOut success!";
    }

    public String timeOutHandler(){
        return "timeOut failure";
    }

    @GetMapping("/breaker")
    @HystrixCommand(fallbackMethod ="breakerHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "10000"),
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),//快照时间窗口内请求次数阈值，没达到即使失败百分比达到阈值也不会开启断路器
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60"),//失败百分比阈值
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000")//快照时间窗口,通过在快照时间范围内统计请求和失败数决定是否打开断路器
    })
    public Long breaker(@RequestParam Integer divide){
        return System.currentTimeMillis()/divide;
    }

    public Long breakerHandler(Integer divide){
        return null;
    }

    @GetMapping("send")
    public String sendKafkaMsg(String msg){
        personService.sendKafkaMsg(msg);
        return "success";
    }

    @GetMapping("redis")
    public void redisTest(){
        personService.redisTest();
    }
}
